package info.xmlprint.core.innerlink;

import info.xmlprint.util.FileUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

public class BaseGroup implements Serializable {
	private static final long serialVersionUID = 9131219388210967392L;

	private List<BaseItem> list = new ArrayList<BaseItem>();

	private String rootElementName;

	public BaseGroup(Element element, String typeName) {
		updateByElement(element, typeName);
	}

	public BaseGroup(String name) {
		rootElementName = name;
	}

	public void add(BaseItem item) {
		list.add(item);
	}

	public List<BaseItem> getItems() {
		return list;
	}

	public String getRootElementName() {
		return rootElementName;
	}

	/*
	 * BaseGroup nach xmlDocument transformieren
	 */
	public Document getXmlDoc() {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement(rootElementName);
		for (BaseItem item : getItems()) {
			root.add(item.getXmlDoc().getRootElement());
		}
		return doc;
	}

	public BaseGroup objClone() {
		BaseGroup clone = (BaseGroup) FileUtil.objClone(this);
		return clone;
	}

	public void remove(BaseItem item) {
		list.remove(item);
	}

	public void updateByElement(Node n, String typeName) {
		if (n == null) {
			return;
		}
		Element elem;
		String name;
		BaseItem item;
		for (Object obj : n.selectNodes("*")) {
			elem = (Element) obj;
			name = elem.getName();
			if (name.equals(typeName) && typeName.equals(InnerLink.ROOT_ELEMENT)) {
				item = new InnerLink();
			} else {
				item = new BaseItem(name);
			}
			item.updateByElement(elem);
			add(item);
		}
	}
}
